package LocalStorage

import (
	"KumquatDrivesServices/utils"
	"bytes"
	"fmt"
	"github.com/nfnt/resize"
	"github.com/sirupsen/logrus"
	ffmpeg_go "github.com/u2takey/ffmpeg-go"
	"image"
	"image/jpeg"
	"os"
	"path/filepath"
)

func (Le LocalEngine) CreateVideoThumbnail(srcPath string) (string, error) {
	buf := bytes.NewBuffer(nil)
	if err := ffmpeg_go.Input(srcPath).
		Filter("select", ffmpeg_go.Args{fmt.Sprintf("gte(n,%d)", 1)}).
		Output("pipe:", ffmpeg_go.KwArgs{"vframes": 1, "format": "image2", "vcodec": "mjpeg"}).
		WithOutput(buf).
		Run(); err != nil {
		logrus.Errorf("生成视频缩略图失败，失败原因 %s", err)
		return "", err
	}
	// 解码图片
	img, _, DecodeErr := image.Decode(bytes.NewReader(buf.Bytes()))
	if DecodeErr != nil {
		return "", DecodeErr
	}

	// 获取原始图片的尺寸
	bounds := img.Bounds()
	originalWidth := bounds.Max.X - bounds.Min.X
	originalHeight := bounds.Max.Y - bounds.Min.Y
	// 计算新的高度以保持宽高比
	newHeight := 200 * originalHeight / originalWidth
	// 使用nfnt/resize库进行图片缩放
	resizedImg := resize.Resize(200, uint(newHeight), img, resize.Lanczos3)
	outPath := filepath.Join(filepath.Dir(srcPath), "cover", utils.GetBaseNameWithoutExt(srcPath)+".jpg")
	if err := utils.CreatePath(outPath); err != nil {
		return "", err
	}
	// 创建输出文件
	outFile, CreateErr := os.Create(outPath)
	if CreateErr != nil {
		return "", CreateErr
	}
	defer outFile.Close()
	// 根据图片格式进行编码并保存压缩后的图片
	if err := jpeg.Encode(outFile, resizedImg, &jpeg.Options{Quality: 50}); err != nil {
		return "", err
	}
	return outPath, nil
}
